<template>
  <div class="registration-list">
    <!-- 顶部操作栏 -->
    <div class="header-actions">
      <div class="left-actions">
        <el-button 
          type="primary" 
          @click="handleAdd"
        >
          <el-icon><Plus /></el-icon>
          {{ isAthlete ? '我要报名' : '新增报名' }}
        </el-button>
        <el-button 
          type="danger" 
          @click="handleBatchDelete"
          :disabled="selectedRegistrations.length === 0"
          v-if="!isAthlete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
      <div class="right-actions" v-if="!isAthlete">
        <el-button @click="handleImport">
          <el-icon><Upload /></el-icon>
          导入报名
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出报名
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="请输入运动员姓名、工号或项目名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="searchForm.auditStatus" placeholder="请选择状态" clearable style="width: 140px;">
            <el-option label="全部" :value="null"/>
            <el-option label="待审核" :value="0"/>
            <el-option label="审核通过" :value="1"/>
            <el-option label="审核拒绝" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="运动员" v-if="!isAthlete">
          <el-select v-model="searchForm.athleteId" placeholder="请选择运动员" clearable filterable style="width: 160px;">
            <el-option 
              v-for="athlete in athletes" 
              :key="athlete.id" 
              :label="`${athlete.realName}(${athlete.workNumber})`" 
              :value="athlete.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="比赛项目">
          <el-select v-model="searchForm.eventId" placeholder="请选择项目" clearable filterable style="width: 160px;">
            <el-option 
              v-for="event in events" 
              :key="event.id" 
              :label="event.eventName" 
              :value="event.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 报名列表 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="registrationList" 
        :loading="loading" 
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="athleteName" label="运动员姓名" min-width="100" show-overflow-tooltip />
        <el-table-column prop="athleteNumber" label="学号" min-width="110" show-overflow-tooltip />
        <el-table-column prop="eventName" label="项目名称" min-width="140" show-overflow-tooltip />
        <el-table-column prop="eventCode" label="项目编码" min-width="100" show-overflow-tooltip />
        <el-table-column prop="registrationNumber" label="报名编号" min-width="110" show-overflow-tooltip />
        <el-table-column prop="teamName" label="团队名称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="raceNumber" label="参赛号码" min-width="90" show-overflow-tooltip />
        <el-table-column prop="auditStatus" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getAuditStatusTagType(row.auditStatus)">
              {{ getAuditStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registrationTime" label="报名时间" min-width="140">
          <template #default="{ row }">
            {{ formatDateTime(row.registrationTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '取消' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" :width="isAthlete ? '160' : '240'" fixed="right">
          <template #default="{ row }">
            <el-button 
              link 
              type="primary" 
              @click="handleViewDetail(row)"
            >
              查看
            </el-button>
            <el-button 
              link 
              type="primary" 
              @click="handleEdit(row)"
              v-if="row.auditStatus === 0 && (isAthlete ? isMyRegistration(row) : true)"
            >
              编辑
            </el-button>
            <el-button 
              link 
              type="info" 
              @click="handleAssignNumber(row)"
              v-if="!isAthlete && row.auditStatus === 1 && !row.raceNumber"
            >
              分配号码
            </el-button>
            <el-button 
              link 
              type="warning" 
              @click="handleCancel(row)"
              v-if="(row.auditStatus === 0 || row.auditStatus === 1) && (isAthlete ? isMyRegistration(row) : true)"
            >
              取消
            </el-button>
            <el-button 
              link 
              type="danger" 
              @click="handleDelete(row)"
              v-if="!isAthlete || (isAthlete && isMyRegistration(row))"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 报名表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleDialogClose"
      @opened="handleDialogOpened"
    >
      <el-form
        ref="registrationFormRef"
        :model="registrationForm"
        :rules="registrationFormRules"
        label-width="120px"
      >
        <el-form-item label="运动员" prop="athleteId">
          <!-- 运动员用户：显示只读的自己信息 -->
          <el-input 
            v-if="isAthlete" 
            :value="getAthleteDisplayText()" 
            readonly 
            style="width: 100%;"
            placeholder="当前登录运动员"
          />
          <!-- 管理员用户：可选择运动员 -->
          <el-select 
            v-else
            v-model="registrationForm.athleteId" 
            placeholder="请选择运动员" 
            filterable 
            style="width: 100%;"
          >
            <el-option 
              v-for="athlete in athletes" 
              :key="athlete.id" 
              :label="`${athlete.realName}(${athlete.workNumber}) - ${athlete.className}`" 
              :value="athlete.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="比赛项目" prop="eventId">
          <el-select v-model="registrationForm.eventId" placeholder="请选择比赛项目" filterable style="width: 100%;">
            <el-option 
              v-for="event in events" 
              :key="event.id" 
              :label="`${event.eventName} - ${event.competitionTime}`" 
              :value="event.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="报名编号">
          <el-input 
            v-model="registrationForm.registrationNumber" 
            placeholder="请输入报名编号" 
          />
        </el-form-item>
        
        <el-form-item label="团队名称">
          <el-input 
            v-model="registrationForm.teamName" 
            placeholder="请输入团队名称（团体项目）" 
          />
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input 
            v-model="registrationForm.remarks" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="报名详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="运动员姓名">{{ registrationDetail.athleteName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="学号">{{ registrationDetail.studentNumber || registrationDetail.athleteNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ getAthleteGenderText(registrationDetail.athleteGender) }}</el-descriptions-item>
        <el-descriptions-item label="院系">{{ registrationDetail.department || '-' }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ registrationDetail.className || registrationDetail.athleteClass || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ registrationDetail.phone || registrationDetail.athletePhone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="比赛项目">{{ registrationDetail.eventName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="项目编码">{{ registrationDetail.eventCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="项目类型">{{ getEventTypeText(registrationDetail.eventType) }}</el-descriptions-item>
        <el-descriptions-item label="性别限制">{{ getGenderLimitText(registrationDetail.genderLimit) }}</el-descriptions-item>
        <el-descriptions-item label="年龄分组">{{ registrationDetail.ageGroup || '-' }}</el-descriptions-item>
        <el-descriptions-item label="成绩单位">{{ registrationDetail.unit || '-' }}</el-descriptions-item>
        <el-descriptions-item label="比赛时间">{{ formatDateTime(registrationDetail.competitionTime) }}</el-descriptions-item>
        <el-descriptions-item label="比赛地点">{{ registrationDetail.venue || '-' }}</el-descriptions-item>
        <el-descriptions-item label="报名编号">{{ registrationDetail.registrationNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="团队名称">{{ registrationDetail.teamName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="参赛号码">{{ registrationDetail.raceNumber || '未分配' }}</el-descriptions-item>
        <el-descriptions-item label="报名状态">
          <el-tag :type="getAuditStatusTagType(registrationDetail.auditStatus)">
            {{ getAuditStatusText(registrationDetail.auditStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="报名时间">{{ formatDateTime(registrationDetail.registrationTime) }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getStatusTagType(registrationDetail.status)">
            {{ getStatusText(registrationDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ formatDateTime(registrationDetail.auditTime || registrationDetail.reviewTime) }}</el-descriptions-item>
        <el-descriptions-item label="审核人">{{ registrationDetail.auditUserName || registrationDetail.reviewerName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审核备注" :span="2">{{ registrationDetail.auditRemark || registrationDetail.reviewRemark || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ registrationDetail.remarks || registrationDetail.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>


    <!-- 分配号码对话框 -->
    <el-dialog v-model="numberDialogVisible" title="分配参赛号码" width="400px">
      <el-form ref="numberFormRef" :model="numberForm" :rules="numberFormRules" label-width="100px">
        <el-form-item label="参赛号码" prop="raceNumber">
          <el-input 
            v-model="numberForm.raceNumber" 
            placeholder="请输入参赛号码" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="numberDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleNumberSubmit" :loading="numberLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { 
  getRegistrationList, createRegistration, updateRegistration, deleteRegistration, 
  batchDeleteRegistrations, getRegistrationDetail, 
  cancelRegistration, assignRaceNumber
} from '@/api/registration'
import { getAthleteList } from '@/api/athlete'
import { getEventList } from '@/api/event'
import {
  Plus, Search, Refresh, Delete, Upload, Download
} from '@element-plus/icons-vue'

// 用户状态
const userStore = useUserStore()

// 权限检查 - 取消权限认证，所有登录用户都可以访问
const hasPermission = (permission) => {
  return true
}

// 判断是否为运动员
const isAthlete = computed(() => {
  return userStore.roles.includes('ATHLETE') || 
         userStore.roles.includes('athlete') || 
         (userStore.userInfo?.username && userStore.userInfo.username.startsWith('athlete'))
})

// 当前运动员显示名称
const currentAthleteDisplayName = computed(() => {
  console.log('计算 currentAthleteDisplayName:', {
    isAthlete: isAthlete.value,
    userInfo: userStore.userInfo,
    athletesCount: athletes.value.length
  })
  
  if (!isAthlete.value || !userStore.userInfo) return '当前登录运动员'
  
  const userInfo = userStore.userInfo
  console.log('当前用户信息:', userInfo)
  
  // 尝试从运动员列表中找到当前用户对应的运动员信息
  const currentAthlete = athletes.value.find(athlete => 
    athlete.realName === userInfo.realName
  )
  
  console.log('找到的运动员:', currentAthlete)
  
  if (currentAthlete) {
    const displayName = `${currentAthlete.realName}(${currentAthlete.studentNumber || currentAthlete.workNumber}) - ${currentAthlete.className || '当前用户'}`
    console.log('显示名称:', displayName)
    return displayName
  }
  
  // 如果找不到运动员记录，使用用户信息
  const fallbackName = `${userInfo.realName || userInfo.username}(${userInfo.username}) - 当前用户`
  console.log('备用显示名称:', fallbackName)
  return fallbackName
})

// 当前运动员ID
const currentAthleteId = ref(null)

// 获取运动员显示文本
const getAthleteDisplayText = () => {
  console.log('=== getAthleteDisplayText 调用 ===')
  console.log('isAthlete:', isAthlete.value)
  console.log('userStore.userInfo:', userStore.userInfo)
  console.log('athletes.value.length:', athletes.value.length)
  
  if (!isAthlete.value) {
    console.log('不是运动员用户')
    return '请选择运动员'
  }
  
  if (!userStore.userInfo) {
    console.log('用户信息为空')
    return '获取用户信息中...'
  }
  
  const userInfo = userStore.userInfo
  console.log('当前用户详细信息:', JSON.stringify(userInfo, null, 2))
  
  // 优先从运动员列表中查找完整信息
  if (athletes.value.length > 0) {
    const currentAthlete = athletes.value.find(athlete => 
      athlete.realName === userInfo.realName ||
      athlete.workNumber === userInfo.username ||
      athlete.studentNumber === userInfo.username
    )
    
    if (currentAthlete) {
      // 优先使用学号，其次使用工号
      const number = currentAthlete.studentNumber || currentAthlete.workNumber
      const displayText = `${currentAthlete.realName}(${number})`
      console.log('从运动员列表构建显示文本:', displayText)
      return displayText
    }
  }
  
  // 如果找不到运动员记录，使用用户基本信息
  if (userInfo.realName) {
    const displayText = `${userInfo.realName}(${userInfo.username})`
    console.log('使用用户信息构建显示文本:', displayText)
    return displayText
  } else if (userInfo.username) {
    const displayText = `${userInfo.username}(${userInfo.username})`
    console.log('使用用户名构建显示文本:', displayText)
    return displayText
  }
  
  console.log('用户信息不完整，返回默认文本')
  return '当前登录运动员'
}

// 加载当前运动员ID
const loadCurrentAthleteId = async () => {
  if (!isAthlete.value || !userStore.userInfo) return
  
  try {
    // 从运动员列表中找到当前用户对应的运动员记录
    const currentUserName = userStore.userInfo.realName
    const currentAthlete = athletes.value.find(athlete => 
      athlete.realName === currentUserName
    )
    
    if (currentAthlete) {
      currentAthleteId.value = currentAthlete.id
    } else {
      console.warn('未找到当前用户对应的运动员记录')
      ElMessage.warning('未找到您的运动员信息，请联系管理员')
    }
  } catch (error) {
    console.error('获取当前运动员ID失败:', error)
  }
}

// 判断是否是我的报名记录
const isMyRegistration = (row) => {
  if (!isAthlete.value || !userStore.userInfo) return false
  return row.athleteName === userStore.userInfo.realName
}

// 响应式数据
const loading = ref(false)
const registrationList = ref([])
const selectedRegistrations = ref([])
const athletes = ref([])
const events = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  auditStatus: null,
  athleteId: null,
  eventId: null
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单对话框
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentRegistrationId = ref(null)
const submitLoading = ref(false)
const registrationFormRef = ref(null)

// 详情对话框
const detailDialogVisible = ref(false)
const registrationDetail = ref({})


// 分配号码对话框
const numberDialogVisible = ref(false)
const numberLoading = ref(false)
const numberFormRef = ref(null)
const currentNumberId = ref(null)

// 报名表单
const registrationForm = reactive({
  athleteId: null,
  eventId: null,
  registrationNumber: '',
  teamName: '',
  remarks: ''
})


// 分配号码表单
const numberForm = reactive({
  raceNumber: ''
})

// 表单验证规则
const registrationFormRules = {
  athleteId: [
    { required: true, message: '请选择运动员', trigger: 'change' }
  ],
  eventId: [
    { required: true, message: '请选择比赛项目', trigger: 'change' }
  ]
}


const numberFormRules = {
  raceNumber: [
    { required: true, message: '请输入参赛号码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]+$/, message: '参赛号码只能包含字母和数字', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑报名' : '新增报名'
})

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取审核状态文本
const getAuditStatusText = (auditStatus) => {
  const statusMap = {
    0: '待审核',
    1: '审核通过',
    2: '审核拒绝'
  }
  return statusMap[auditStatus] || '未知'
}

// 获取审核状态标签类型
const getAuditStatusTagType = (auditStatus) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return typeMap[auditStatus] || ''
}

// 获取运动员性别文本
const getAthleteGenderText = (gender) => {
  const genderMap = {
    1: '男',
    2: '女'
  }
  return genderMap[gender] || '-'
}

// 获取项目类型文本
const getEventTypeText = (type) => {
  const typeMap = {
    1: '个人项目',
    2: '团体项目'
  }
  return typeMap[type] || '-'
}

// 获取性别限制文本
const getGenderLimitText = (limit) => {
  const limitMap = {
    0: '不限',
    1: '男子',
    2: '女子'
  }
  return limitMap[limit] || '-'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '正常',
    2: '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || ''
}

// 加载报名列表
const loadRegistrationList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    // 如果是运动员，只查询自己的报名记录
    if (isAthlete.value && userStore.userInfo) {
      // 清除其他搜索条件，强制只显示自己的记录
      params.keyword = userStore.userInfo.realName
      params.athleteId = null // 确保不使用其他运动员筛选
      // 或者如果后端支持直接通过athleteId查询
      // params.athleteId = userStore.userInfo.athleteId
      
      console.log('运动员用户查询参数:', params)
    }
    
    const response = await getRegistrationList(params)
    registrationList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载报名列表失败:', error)
    ElMessage.error('加载报名列表失败')
  } finally {
    loading.value = false
  }
}

// 加载运动员列表
const loadAthletes = async () => {
  try {
    const response = await getAthleteList({ current: 1, size: 1000, status: 1 })
    athletes.value = response.data.records || []
  } catch (error) {
    console.error('加载运动员列表失败:', error)
  }
}

// 加载比赛项目列表
const loadEvents = async () => {
  try {
    const response = await getEventList({ current: 1, size: 1000, status: 1 })
    events.value = response.data.records || []
  } catch (error) {
    console.error('加载比赛项目列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadRegistrationList()
}

// 重置搜索
const handleReset = () => {
  if (isAthlete.value) {
    // 运动员用户重置时，保持显示自己的记录
    Object.assign(searchForm, {
      keyword: userStore.userInfo?.realName || '', // 保持自己的姓名
      auditStatus: null,
      athleteId: null,
      eventId: null
    })
  } else {
    // 管理员用户可以完全重置
    Object.assign(searchForm, {
      keyword: '',
      auditStatus: null,
      athleteId: null,
      eventId: null
    })
  }
  handleSearch()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadRegistrationList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadRegistrationList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedRegistrations.value = selection
}

// 新增报名
const handleAdd = async () => {
  console.log('=== handleAdd 开始 ===')
  
  isEdit.value = false
  currentRegistrationId.value = null
  resetRegistrationForm()
  
  // 确保用户信息已加载
  if (!userStore.userInfo) {
    console.log('重新获取用户信息...')
    await userStore.getUserInfo()
  }
  
  // 确保运动员列表已加载
  if (athletes.value.length === 0) {
    await loadAthletes()
  }
  
  console.log('handleAdd - userStore.userInfo:', userStore.userInfo)
  console.log('handleAdd - isAthlete:', isAthlete.value)
  
  // 如果是运动员用户，自动填入运动员ID
  if (isAthlete.value && userStore.userInfo) {
    await loadCurrentAthleteId()
    if (currentAthleteId.value) {
      registrationForm.athleteId = currentAthleteId.value
    }
  }
  
  console.log('打开对话框前的最终状态:')
  console.log('- isAthlete:', isAthlete.value)
  console.log('- userStore.userInfo:', userStore.userInfo)
  console.log('- getAthleteDisplayText():', getAthleteDisplayText())
  
  dialogVisible.value = true
}

// 编辑报名
const handleEdit = (row) => {
  isEdit.value = true
  currentRegistrationId.value = row.id
  Object.assign(registrationForm, {
    athleteId: row.athleteId,
    eventId: row.eventId,
    registrationNumber: row.registrationNumber || '',
    teamName: row.teamName || '',
    remarks: row.remarks || ''
  })
  dialogVisible.value = true
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const response = await getRegistrationDetail(row.id)
    registrationDetail.value = {
      ...row,
      ...response.data
    }
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取报名详情失败:', error)
    ElMessage.error('获取报名详情失败')
  }
}

// 删除报名
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除报名ID为 ${row.id} 的记录吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteRegistration(row.id)
    ElMessage.success('删除成功')
    loadRegistrationList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除报名失败:', error)
      ElMessage.error('删除报名失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRegistrations.value.length} 条报名记录吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const ids = selectedRegistrations.value.map(item => item.id)
    await batchDeleteRegistrations(ids)
    ElMessage.success('批量删除成功')
    loadRegistrationList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}


// 取消报名
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消报名ID为 ${row.id} 的记录吗？`,
      '取消确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await cancelRegistration(row.id)
    ElMessage.success('取消成功')
    loadRegistrationList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消报名失败:', error)
      ElMessage.error('取消报名失败')
    }
  }
}

// 分配号码
const handleAssignNumber = (row) => {
  currentNumberId.value = row.id
  numberForm.raceNumber = ''
  numberDialogVisible.value = true
}

// 提交分配号码
const handleNumberSubmit = async () => {
  try {
    await numberFormRef.value.validate()
    numberLoading.value = true

    await assignRaceNumber(currentNumberId.value, numberForm)
    ElMessage.success('分配号码成功')
    numberDialogVisible.value = false
    loadRegistrationList()
  } catch (error) {
    console.error('分配号码失败:', error)
    ElMessage.error('分配号码失败')
  } finally {
    numberLoading.value = false
  }
}

// 导入报名
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 导出报名
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 提交表单
const handleSubmit = async () => {
  if (!registrationFormRef.value) return
  
  try {
    await registrationFormRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      await updateRegistration(currentRegistrationId.value, registrationForm)
      ElMessage.success('更新成功')
    } else {
      await createRegistration(registrationForm)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadRegistrationList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 对话框打开后的处理
const handleDialogOpened = () => {
  if (!isEdit.value) {
    resetRegistrationForm()
  }
}

// 对话框关闭处理
const handleDialogClose = (done) => {
  resetRegistrationForm()
  dialogVisible.value = false
  if (typeof done === 'function') {
    done()
  }
}

// 重置表单
const resetRegistrationForm = () => {
  if (registrationFormRef.value) {
    registrationFormRef.value.resetFields()
    registrationFormRef.value.clearValidate()
  }
  
  Object.assign(registrationForm, {
    athleteId: null,
    eventId: null,
    registrationNumber: '',
    teamName: '',
    remarks: ''
  })
}

// 组件挂载时加载数据
onMounted(async () => {
  console.log('=== RegistrationList onMounted ===')
  
  // 确保用户信息已加载
  if (!userStore.userInfo) {
    console.log('用户信息未加载，重新获取...')
    await userStore.getUserInfo()
  }
  
  console.log('onMounted - userStore.userInfo:', userStore.userInfo)
  console.log('onMounted - isAthlete:', isAthlete.value)
  
  // 如果是运动员，预设搜索条件为自己的姓名
  if (isAthlete.value && userStore.userInfo) {
    searchForm.keyword = userStore.userInfo.realName
    console.log('设置搜索关键词:', searchForm.keyword)
  }
  
  loadRegistrationList()
  loadAthletes()
  loadEvents()
})
</script>

<style scoped>
.registration-list {
  padding: 20px;
  width: 100%;
  max-width: 100%;
  overflow-x: auto;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.left-actions,
.right-actions {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
  width: 100%;
}

/* 表格样式优化 */
.table-card :deep(.el-table) {
  width: 100% !important;
}

.table-card :deep(.el-table__body-wrapper) {
  width: 100% !important;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
